package com.cf.studiomanage.controller;

import com.cf.studiomanage.entity.User;
import com.cf.studiomanage.service.UserService;
import com.cf.studiomanage.util.JwtUtil;
import com.cf.studiomanage.util.R;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户模块", description = "提供用户注册、登录、信息查询与修改等功能")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户提交信息进行注册")
    public R register(@RequestBody User user) {
        boolean success = userService.register(user);
        return success ? R.ok("注册成功") : R.error("注册失败");
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "根据账号和密码登录，成功后返回 JWT token 和用户信息")
    public R login(@RequestBody Map<String, String> map, HttpServletResponse response) {
        String account = map.get("account");
        String password = map.get("password");

        User user = userService.login(account, password);
        if (user == null) {
            return R.error("账号或密码错误");
        }

        String token = JwtUtil.generateToken(user.getId(), user.getRole());
        response.setHeader("Authorization", "Bearer " + token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return R.ok("登录成功")
                .data("token", token)
                .data("user", user);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取用户信息", description = "根据用户ID获取详细信息")
    public R getUser(@PathVariable Long id) {
        User user = userService.getById(id);
        return user != null ? R.ok().data("user", user) : R.error("用户不存在");
    }

    @PostMapping("/update")
    @Operation(summary = "修改用户资料", description = "用户可更新个人信息（除密码）")
    public R updateProfile(@RequestBody User user) {
        boolean success = userService.updateProfile(user);
        return success ? R.ok("更新成功") : R.error("更新失败");
    }

    @PostMapping("/updatePassword")
    @Operation(summary = "修改密码", description = "用户通过旧密码或身份验证修改密码")
    public R updatePassword(@RequestBody Map<String, String> map) {
        Long id = Long.parseLong(map.get("id"));
        String newPassword = map.get("newPassword");
        boolean success = userService.updatePassword(id, newPassword);
        return success ? R.ok("密码修改成功") : R.error("密码修改失败");
    }

    @GetMapping("/info")
    @Operation(summary = "获取当前登录用户信息", description = "从请求中获取 userId 和角色，前端常用于身份判断")
    public R getInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        String role = (String) request.getAttribute("role");
        return R.ok().data("userId", userId).data("role", role);
    }
}
